# -*- coding: utf-8 -*-
# django ORM based backend


from twisted.internet import threads
from django.db import settings, router
from grdlog.models import Event, Source

class DjangoConf(object):
    """ Django's settings as conf source. """
    
    def __init__(self):
        db = router.db_for_write(Event)
        # maybe raise some exception if !=
        if db == router.db_for_write(Source):
            db = settings.DATABASES[db]
            # explicit requirement for postgres!
            if db['ENGINE'] in ('django.db.backends.postgresql_psycopg2',
                                'django.db.backends.postgresql'):
                self.dsn = {
                        'database': db.get('NAME'),
                        'user': db.get('USER'),
                        'password': db.get('PASSWORD'),
                        'host': db.get('HOST'),
                        'port': db.get('PORT')
                        }

class DjangoDB(object):
    
    def insertEntry(self, values):
        values.update({'date': values['time']})
        threads.deferToThread(lambda : Event.objects.create(**values))
    
    def __init__(self, _):
        self.sources = Source.objects.all()
